package com.nineclock.approve.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.nineclock.approve.nodeResolver.ProcessNodeResolver;
import com.nineclock.approve.nodeResolver.ProcessNodeResolverFactory;
import com.nineclock.approve.pojo.ApproveDefinition;
import com.nineclock.approve.service.ActivitiService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.BpmnAutoLayout;
import org.activiti.bpmn.converter.BpmnXMLConverter;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.Process;
import org.activiti.engine.RepositoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class ActivitiServiceImpl implements ActivitiService {
    @Autowired
    RepositoryService repositoryService;
    @Override
    public void deployProcessToActiviti(ApproveDefinition definition) {
        BpmnModel bpmnModel = new BpmnModel();

        //创建流程对象
        Process process = new Process();
        process.setId("process_"+definition.getId());

        //获取流程json
        String flowJson = definition.getFlowJson();
        JSONArray jsonArray = JSONUtil.parseArray(flowJson);
        this.addFlowElementToPress(process,jsonArray);

        //添加流程
        bpmnModel.addProcess(process);
        //流程自动布局
        new BpmnAutoLayout(bpmnModel).execute();
        repositoryService.createDeployment()
                .name(definition.getName())
                .addBpmnModel(definition.getName()+".bpmn",bpmnModel)
                .deploy();
        //输出XML, 便于测试
        BpmnXMLConverter converter = new BpmnXMLConverter();
        byte[] bytes = converter.convertToXML(bpmnModel);

        log.info("-------> 转换BpmnModel为XML数据 .");
        System.out.println(new String(bytes));
        log.info("-------> XML文件转换并输出完毕 . ");
    }

    private void addFlowElementToPress(Process process, JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.size() == 0){
            return;
        }

        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject  currentNode = (JSONObject) jsonArray.get(i);
            JSONObject nextNode = null;
            if (i<jsonArray.size()-1){
                nextNode = (JSONObject) jsonArray.get(i+1);
            }
            String type = currentNode.getStr("type");
            //根据type字段获取不同类型的节点处理器
            ProcessNodeResolver nodeResolver = ProcessNodeResolverFactory.getInstance(type);
            //添加流程节点到activiti中
            nodeResolver.addFlowNodeToActiviti(process, currentNode, nextNode);
        }

    }

    @Override
    public void deleteProcessFromActiviti(ApproveDefinition definition) {

    }
}
